/**
 * 
 */
package com.feizhi.common.upload.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

import com.feizhi.common.ErrCode;
import com.feizhi.common.OperateResult;
import com.feizhi.common.stream.StreamUtil;
import com.feizhi.common.upload.UploadTmpFileUtil;
import com.feizhi.common.upload.bean.UploadResult;

/**
 * 临时文件上传
 * 
 * @author shuaqiu 2013年11月17日
 * 
 */
@RequestMapping(value = "/upload")
@Controller
public class UploadTmpController {
	private static final Log log = LogFactory.getLog(UploadTmpController.class);

	@RequestMapping(method = RequestMethod.POST, produces = "text/plain;charset=utf-8")
	@ResponseBody
	public Object upload(WebRequest req, @RequestParam String path,
			@RequestPart("uploadedfiles[]") List<MultipartFile> files) {

		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			List<UploadResult> results = new ArrayList<UploadResult>(
					files.size());
			for (MultipartFile file : files) {
				UploadResult res = new UploadResult(file);

				inputStream = new BufferedInputStream(file.getInputStream());
				File tmpFile = getTmpFile(req, path, res);
				if (tmpFile == null) {
					continue;
				}
				outputStream = new FileOutputStream(tmpFile);

				StreamUtils.copy(inputStream, outputStream);

				res.setUri(UploadTmpFileUtil.getRelativeUri(tmpFile));
				results.add(res);
			}

			return new OperateResult(true, results);
		} catch (IOException e) {
			if (log.isErrorEnabled()) {
				log.error(e.getMessage(), e);
			}
			return new OperateResult(ErrCode.EXCEPTION, e.getMessage());
		} finally {
			StreamUtil.close(inputStream, log);
			StreamUtil.close(outputStream, log);
		}
	}

	private File getTmpFile(WebRequest req, String path, UploadResult file) {
		File tmpFolder = getTmpFolder(req, path);
		File tmpFile = null;
		do {
			String filename = UUID.randomUUID().toString() + file.getExt();
			tmpFile = new File(tmpFolder, filename);
		} while (tmpFile.exists());
		return tmpFile;
	}

	/**
	 * @param req
	 * @param path
	 * @return
	 */
	private File getTmpFolder(WebRequest req, String path) {
		String sessionId = req.getSessionId();

		File tmpFolder = new File(UploadTmpFileUtil.getTmpDir(), sessionId);
		tmpFolder = new File(tmpFolder, path);
		if (!tmpFolder.exists()) {
			tmpFolder.mkdirs();
		}
		log.debug("tmp folder is --> " + tmpFolder.getAbsolutePath());
		return tmpFolder;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult remove(@RequestBody Map<String, String> map) {
		String uri = map.get("uri");
		File tmpFile = UploadTmpFileUtil.getTmpFile(uri);
		boolean isDeleted = tmpFile.delete();
		return new OperateResult(isDeleted, uri);
	}
}
